<template>
  <div id="userRegisterPage">
    <h2 class="title">用户注册</h2>
    <a-form
      style="max-width: 480px; margin: 0 auto"
      :model="formState"
      name="basic"
      label-align="left"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 20 }"
      autocomplete="off"
      @finish="onFinish"
      @finishFailed="onFinishFailed"
    >
      <a-form-item
        label="账号"
        name="username"
        :rules="[{ required: true, message: '请输入登录账号' }]"
      >
        <a-input v-model:value="formState.username" placeholder="请输入登录账号" />
      </a-form-item>

      <a-form-item
        label="密码"
        name="password"
        :rules="[
          { required: true, message: '登录密码不能为空' },
          { min: 6, message: '密码不能小于6位' },
        ]"
      >
        <a-input-password v-model:value="formState.password" placeholder="请输入登录密码" />
      </a-form-item>

      <a-form-item
        label="确认密码"
        name="check_pwd"
        :rules="[
          { required: true, message: '确认密码不能为空' },
          { min: 6, message: '确认密码不能小于6位' },
        ]"
      >
        <a-input-password v-model:value="formState.check_pwd" placeholder="请输入确认密码" />
      </a-form-item>

      <a-form-item :wrapper-col="{ offset: 4, span: 20 }">
        <a-button type="primary" html-type="submit">注册</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<style scoped>
#userRegisterPage .title {
  text-align: center;
  margin: 0 auto 16px;
}
</style>

<script lang="ts" setup>
import { reactive } from 'vue'
import { userRegister } from '@/api/user.ts'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'

interface FormState {
  username: string
  password: string
  check_pwd: string
}

const formState = reactive<FormState>({
  username: '',
  password: '',
  check_pwd: '',
})

const router = useRouter()
//提交表单进行注册操作
const onFinish = async (values: any) => {
  //两次密码是否一致
  if (formState.password !== formState.check_pwd) {
    message.error('两次输入的密码不一致')
    return
  }
  const res = await userRegister(values)
  //注册判断
  //如果注册成功,跳转登录页面
  if (res.data.code === 1) {
    //给用户点儿提示信息
    message.success('注册成功')
    //路由跳转
    await router.push({
      path: '/user/login',
      replace: true,
    })
  } else {
    message.error('注册失败' + (res.data.msg ?? '未知错误'))
  }

  console.log('注册返回')
  console.log(res)
}

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo)
}
</script>
